package com.rabbitmq.transaction;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @className: Transaction
 * @description: 事务机制
 * @date: 2020/5/14
 * @author: cakin
 */
@Slf4j
public class Transaction {
    /**
     * 交换器
     */
    private static final String EXCHANGE_NAME = "exchange_demo";
    /**
     * 路由键
     */
    private static final String ROUTING_KEY = "routingkey_demo";
    /**
     * 队列
     */
    private static final String QUEUE_NAME = "queue_tx";

    public static void main( String[] args ) {
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);

            try {
                // 开启事务：将当前信道设置为事务模式
                channel.txSelect();
                channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, false,
                        MessageProperties.PERSISTENT_TEXT_PLAIN, "事务".getBytes());
                // 模拟异常
                 int result = 1 / 0;
                // 提交事务
                channel.txCommit();
            } catch (Exception e) {
                log.info("catch Exception");
                // 回滚事务
                channel.txRollback();
                // 消息重发
                log.info("增加消息重发逻辑");
            }
            ConnectionUtils.close(channel, connection);
        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}
